package com.cycrix.tcp;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;

public class TcpText extends TcpObject {
	
	private String _text;
	
	public TcpText() {
		_text = "";
	}
	
	public TcpText(String text) {
		_text = text;
	}

	@Override
	public int GetSize() {
		try {
			return UTF8Encoder.encode(CharBuffer.wrap(_text)).limit() + 12;
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		return -1;
	}

	@Override
	public int GetStream(byte[] buffer, int size) {
		ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
		
		// Write code
		int code = TcpConnection.ENUM_TEXT;
		byteBuffer.putInt(4, code);
		
		// Write text
		ByteBuffer textByteBuffer = null;
		try {
			textByteBuffer = UTF8Encoder.encode(CharBuffer.wrap(_text));
			textByteBuffer.get(buffer, 12, textByteBuffer.limit());
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		
		// write size
		int len = textByteBuffer.limit() + 12;
		byteBuffer.putInt(0, len);
		
		// write checksum
		byteBuffer.putInt(8, len ^ code);
		
		return len;
	}

	@Override
	public TcpObject FromStream(byte[] buffer) {
		
		ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
		byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
		int len = byteBuffer.getInt(0);		
		byteBuffer.position(12);
		byteBuffer.limit(len);
		try {
			_text = UTF8Decoder.decode(byteBuffer).toString();
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		
		return this;
	}

	@Override
	public int GetType() {
		return TcpConnection.ENUM_TEXT;
	}

	public String GetText() {
		return _text;
	}
	
	public TcpText SetText(String text) {
		_text = text;
		return this;
	}
}
